const log4js      = require('../../data/log');
const logger      = log4js.getLogger('info');
const constants   = require('../../data/constants');
const channelModel= require('../../model/channel');
const server      = require('../../sip/server');
const mediaserverModel = require('../../model/mediaserver');
const deviceModel = require('../../model/device');
const baseCtrl    = require('./basectrl');
/**
 * 子通道
 */
let Channel = {
    calcMediaUrl: async function (parentid, deviceid, types) {
        //TODO: 这里临时写死
        // 获取 device 信息
        const device = await deviceModel.getDeviceByDeviceId(parentid);
        let serverId;
        if (device && device.server_id) {
            serverId = device.server_id;
        } else {
            serverId = 1;
        }
        // 从host是为了获取url urlTls等信息
        let host = await mediaserverModel.getInfoById(serverId);
        const streamId = `v_${parentid}_${deviceid}`;
        // logger.info('调试', host,streamId, parentid, deviceid);
        let str;
        switch (types) {
            case 'hls':
                str = `${host.url}rtp/${streamId}/hls.m3u8`;
                break;
            case 'hlsTls':
                str = `${host.urlTls}rtp/${streamId}/hls.m3u8`;
                break;
            case 'local':
                str = `${host.rtmp_snap}rtp/${streamId}`;
                break;
            case 'flv':
                str = `${host.url}rtp/${streamId}.flv`;
                break;
            case 'flvTls':
                str = `${host.urlTls}rtp/${streamId}.flv`;
                break;
            case 'rtmp_snap':
                str = `${host.rtmp_snap}rtp/${streamId}`;
                break;
            default:
                str = `${host.rtmp}rtp/${streamId}`;
                break;
        }
        return str;
    },
    list:async function(req,res){
        // TODO: 外部接口会用到，暂时去掉了验证
        // if(!basectrl.hasLogin(req, res)){
        //     return;
        // }
        channelModel.list(req.query.parentId).then(async (rows) => {
            // TODO:生成 hls 地址
            let handleRows = [];

            for (let i = 0; i < rows.length; i++) {
                const item = rows[i];
                //TODO: 海康大华的，如果通道大于1，那deviceid和parentid相等就不能用
                // 但JCO的设备，通道等于2时, deviceid和parentid相等是能用的
                if (rows.length > 2 && item.deviceid === item.parentid) {
                    // nvr 的这个通道不用

                } else {
                    item.hls = await Channel.calcMediaUrl(item.parentid, item.deviceid, 'hls');
                    item.hlsTls = await Channel.calcMediaUrl(item.parentid, item.deviceid, 'hlsTls');
                    item.rtmp = await Channel.calcMediaUrl(item.parentid, item.deviceid, 'rtmp');
                    item.flv = await Channel.calcMediaUrl(item.parentid, item.deviceid, 'flv');
                    item.flvTls = await Channel.calcMediaUrl(item.parentid, item.deviceid, 'flvTls');
                    handleRows.push(item);
                }
            }

            // 处理逻辑 ...
            let ret =Object.assign(constants.httpCode.OK , {data:{items:handleRows, total:handleRows.length}});
            res.send(ret);
        }).catch((err) => {
            logger.error('请求列表出现异常', err);
            res.send({'code':1, 'msg':'出现异常' + err});
        });
    },
    deleteByChannelDevice:async function(req, res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        const parentId = req.body.parentId;
        const deviceId = req.body.deviceId;

        channelModel.deleteByDeviceId(parentId, deviceId);
        // 删除缓存信息
        if(constants.registry && constants.registry[parentId] && constants.registry[parentId][deviceId]){
            delete constants.registry[parentId][deviceId];
        }
        let ret =Object.assign(constants.httpCode.OK , {data:{}});
        res.send(ret);
    },
    // 发停止播放指令
    bye: async function (req, res) {
        if (!baseCtrl.hasLogin(req, res)) {
            return;
        }
        logger.log('bye req', req.query);
        let deviceid = req.query.deviceid;
        let channel = req.query.channel;
        await server.bye(deviceid, channel);
        res.send({'code': 0, 'msg': 'success'});
    },
    // 截屏
    snap: async function (req, res) {
        // 暂时注销，可能会导致无法截屏
        // if(!basectrl.hasLogin(req, res)){
        //     return;
        // }
        let deviceid = req.query.deviceid;
        let channel = req.query.channel;
        logger.info(`截图请求,deviceid=${deviceid},channel=${channel}`);
        let url = await Channel.calcMediaUrl(deviceid, channel, 'local');
        // 暂时不截图了，直接返回在线结果
        const ret = await deviceModel.getDeviceByDeviceId(deviceid);
        const channels = await channelModel.list(deviceid);
        logger.info(`数据库结果,deviceid=${deviceid},channel=${channel}`, ret, channels);

        // mediaUtils.snap(url, deviceid, channel).then((ret) => {
        //     logger.info(`截图返回,deviceid=${deviceid},channel=${channel}`,ret);
        //
        //     channelModel.updateSnap(ret.toString(), deviceid, channel).then(() => {
        //         logger.info(`截图更新成功,deviceid=${deviceid},channel=${channel}`,ret);
        //         res.send(Object.assign(constants.httpCode.OK, {data: {}}));
        //     }).catch((err) => {
        //         logger.info(`截图更新失败,deviceid=${deviceid},channel=${channel}`,err);
        //         res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM, {data: {}}));
        //     })
        //
        // }).catch((err) => {
        //     logger.info(`截图异常,deviceid=${deviceid},channel=${channel}`, err);
        //     res.send(Object.assign(constants.httpCode.UNKNOWN, {data: {}}));
        // });
        res.send(Object.assign(constants.httpCode.OK, {data: {
            'items':ret,
            'channels':channels
            }}));
    },
    registry:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        let data = constants.registry;
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    control:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        //TODO:
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    zoom:function(req,res){
        if(!baseCtrl.hasLogin(req, res)){
            return;
        }
        //TODO:
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    },
    move:function(req, res){
        let data = {};
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    }
};
module.exports=Channel;
